<?php
class UserController extends Controller
{
	public function filters()
	{
		return array(
		//   'accessControl',
		);
	}

	public function accessRules()
	{
		return array(
		array('allow',
			   'actions'=>array('index','favorite'),
			   'users'=>array('*'),
		),
		array('allow',
					   'actions'=>array('removefavorite'),
					   'users'=>array('@'),
		),
		array('deny',
	                'users'=>array('*'),
		),
		);
	}
	public function actionIndex()
	{
	 $error=null;
	 $info=null;
	 if(yii::app()->user->isGuest){
	 	Yii::app()->user->setReturnUrl(CController::createUrl("user/index"));
	 	$this->redirect(array('site/login'));
	 }else{
	 	if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null && isset($_POST['MemberDetails'])){
	 		$member_detail = MemberDetails::model()->findByPk(Yii::app()->user->id);
	 		$member_detail->nickname=$_POST['MemberDetails']['nickname'];
	 		if(strlen(utf8_decode($member_detail->nickname))<2 ||strlen(utf8_decode($member_detail->nickname))>8){
	 			$error="昵称长短不符合要求！";
	 		}
	 		elseif(MemberDetails::model()->findAll("nickname='$member_detail->nickname'")!=null){
	 			$error="此昵称已经被占用！";
	 		}else{
	 			$member_detail->save();
	 			$info="您已成功申请使用——".$member_detail->nickname;
	 		}
	 	}
	 	}
	 	$this->render("index", array(
	 			"error"=>$error,
	 			"info"=>$info,
	 	));
	}
	//收藏
	public function actionFavorite($id=null,$page=1,$title="未命名")
	{
		if(yii::app()->user->isGuest){
			Yii::app()->user->setReturnUrl(CController::createUrl("user/index"));
			$this->redirect(array('site/login'));
		}else{
			if($id!=null){
				$favorite = new Favorite();
				$favorite->member_id= Yii::app()->user->id;
				$favorite->favorite_id =$id;
				$favorite->title=$title;
				$favorite->page=$page;
				$favorite->save();

			}
			$favorites = Favorite::model()->findAll("member_id =".Yii::app()->user->id);
			
		$this->render("favorite", array(
		 			"favorites"=>$favorites,
		));
		}
	}
	//删除收藏
	public function actionRemovefavorite($id){
		$favorite = $this->loadFavorite($id);
		if($favorite->member_id ==Yii::app()->user->id ){
			$favorite->delete();
		}
	}
	private function loadFavorite($pk){
		$model = Favorite::model()->findByPk($pk);
		if(isset($model)){
			return $model;
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}		
}